import fs from 'fs';
import path from 'path';
import moment from 'moment';
import { PLUGIN_PATH } from '../function/function.js';

const BACKUP_PATH = path.join(PLUGIN_PATH, 'backup');

export class Backup extends plugin {
    constructor() {
        super({
            name: '[Sm]备份管理',
            dsc: '奴隶市场数据备份管理',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^#?(奴隶|群友|nl)备份$/, fnc: 'createBackup', permission: 'master' },
                { reg: /^#?(奴隶|群友|nl)备份列表$/, fnc: 'listBackups', permission: 'master' },
                { reg: /^#?(奴隶|群友|nl)恢复备份\s*(\d+)$/, fnc: 'restoreBackup', permission: 'master' },
                { reg: /^#?(奴隶|群友|nl)删除备份\s*(\d+)$/, fnc: 'deleteBackup', permission: 'master' }
            ]
        });

        // 确保备份目录存在
        if (!fs.existsSync(BACKUP_PATH)) {
            fs.mkdirSync(BACKUP_PATH, { recursive: true });
        }
    }

    // 创建备份
    async createBackup(e) {
        try {
            const timestamp = moment().format('YYYY-MM-DD_HH-mm-ss');
            const backupDir = path.join(BACKUP_PATH, timestamp);

            // 创建备份目录
            fs.mkdirSync(backupDir);

            // 复制data目录
            this.copyDirectory(
                path.join(PLUGIN_PATH, 'data'),
                path.join(backupDir, 'data')
            );

            // 复制配置文件
            const configPath = path.join('config', 'SlaveMarket_config.yaml');
            if (fs.existsSync(configPath)) {
                fs.copyFileSync(
                    configPath,
                    path.join(backupDir, 'SlaveMarket_config.yaml')
                );
            }

            return e.reply([
                '备份创建成功！\n',
                `备份时间：${timestamp}\n`,
                '可使用 #奴隶备份列表 查看所有备份'
            ]);
        } catch (err) {
            logger.error('创建备份时出错：', err);
            return e.reply('创建备份失败，请查看控制台错误信息');
        }
    }

    // 列出所有备份
    async listBackups(e) {
        try {
            const backups = fs.readdirSync(BACKUP_PATH)
                .filter(dir => fs.statSync(path.join(BACKUP_PATH, dir)).isDirectory())
                .sort((a, b) => b.localeCompare(a)); // 按时间倒序

            if (backups.length === 0) {
                return e.reply('当前没有任何备份');
            }

            const backupList = backups.map((backup, index) => {
                return `${index + 1}. ${backup}`;
            }).join('\n');

            return e.reply([
                '备份列表：\n',
                backupList,
                '\n可使用 #奴隶恢复备份<序号> 恢复指定备份'
            ]);
        } catch (err) {
            logger.error('获取备份列表时出错：', err);
            return e.reply('获取备份列表失败，请查看控制台错误信息');
        }
    }

    // 恢复备份
    async restoreBackup(e) {
        try {
            const backups = fs.readdirSync(BACKUP_PATH)
                .filter(dir => fs.statSync(path.join(BACKUP_PATH, dir)).isDirectory())
                .sort((a, b) => b.localeCompare(a));

            const index = parseInt(e.msg.match(/\d+/)[0]) - 1;
            if (index < 0 || index >= backups.length) {
                return e.reply('无效的备份序号');
            }

            const backupDir = path.join(BACKUP_PATH, backups[index]);

            // 恢复data目录
            this.copyDirectory(
                path.join(backupDir, 'data'),
                path.join(PLUGIN_PATH, 'data')
            );

            // 恢复配置文件
            const backupConfig = path.join(backupDir, 'SlaveMarket_config.yaml');
            if (fs.existsSync(backupConfig)) {
                fs.copyFileSync(
                    backupConfig,
                    path.join('config', 'SlaveMarket_config.yaml')
                );
            }

            return e.reply([
                '备份恢复成功！\n',
                `恢复时间点：${backups[index]}`
            ]);
        } catch (err) {
            logger.error('恢复备份时出错：', err);
            return e.reply('恢复备份失败，请查看控制台错误信息');
        }
    }

    // 删除备份
    async deleteBackup(e) {
        try {
            const backups = fs.readdirSync(BACKUP_PATH)
                .filter(dir => fs.statSync(path.join(BACKUP_PATH, dir)).isDirectory())
                .sort((a, b) => b.localeCompare(a));

            const index = parseInt(e.msg.match(/\d+/)[0]) - 1;
            if (index < 0 || index >= backups.length) {
                return e.reply('无效的备份序号');
            }

            const backupDir = path.join(BACKUP_PATH, backups[index]);
            this.deleteDirectory(backupDir);

            return e.reply([
                '备份删除成功！\n',
                `删除备份：${backups[index]}`
            ]);
        } catch (err) {
            logger.error('删除备份时出错：', err);
            return e.reply('删除备份失败，请查看控制台错误信息');
        }
    }

    // 工具方法：复制目录
    copyDirectory(src, dest) {
        if (!fs.existsSync(dest)) {
            fs.mkdirSync(dest, { recursive: true });
        }

        const entries = fs.readdirSync(src, { withFileTypes: true });

        for (const entry of entries) {
            const srcPath = path.join(src, entry.name);
            const destPath = path.join(dest, entry.name);

            if (entry.isDirectory()) {
                this.copyDirectory(srcPath, destPath);
            } else {
                fs.copyFileSync(srcPath, destPath);
            }
        }
    }

    // 工具方法：删除目录
    deleteDirectory(dir) {
        if (fs.existsSync(dir)) {
            fs.readdirSync(dir).forEach((file) => {
                const curPath = path.join(dir, file);
                if (fs.lstatSync(curPath).isDirectory()) {
                    this.deleteDirectory(curPath);
                } else {
                    fs.unlinkSync(curPath);
                }
            });
            fs.rmdirSync(dir);
        }
    }
} 